<%@page trimDirectiveWhitespaces="true"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<%
//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
//GET PERMISSION
	String name = String.valueOf(session.getAttribute("name"));
	String surname = String.valueOf(session.getAttribute("surname"));
	String role_name = String.valueOf(session.getAttribute("curriculum_role"));
	
	String department_id = String.valueOf(session.getAttribute("department_id"));
			
	System.out.println("name : " + name);///////////////////////////////
	System.out.println("department_id : " + department_id);/////////////////////////
	
	List<String> system_name = new ArrayList<String>();
	
	Permission permission = new Permission(strUser,name);
	permission.setCurriculumCreate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_create"))));
	permission.setCurriculumDelete(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_delete"))));
	permission.setCurriculumRead(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_read"))));
	permission.setCurriculumUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_update"))));
	
	String permiss = "";
	if(permission.getCurriculumCreate()) {
		permiss = permiss + "Add";
	}
	if(permission.getCurriculumUpdate()) {
		if("".equals(permiss)) {
			permiss = permiss + "Edit";
		} else {
			permiss = permiss + " Edit";
		}
	}
	if(permission.getCurriculumRead()) {
		if("".equals(permiss)) {
			permiss = permiss + "Read";
		} else {
			permiss = permiss + " Read";
		}
	}
	if(permission.getCurriculumDelete()) {
		if("".equals(permiss)) {
			permiss = permiss + "Delete";
		} else {
			permiss = permiss + " Delete";
		}
	}

	//check permission
		if(!permission.getCurriculumCreate()){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_home.jsp"> 	
		<%}
	
	System.out.println("in SAVE Course:");////////////////try////////////////
	//get value from tag
	String courseId =  request.getParameter("courseId");
	String courseNameEN = request.getParameter("courseNameEN");
	String courseNameTH = request.getParameter("courseNameTH");
	String credit = request.getParameter("credit");
	String lecture = request.getParameter("lecture");
	String lab = request.getParameter("lab");
	String selfLearn = request.getParameter("selfLearn");
	String details = request.getParameter("details");
			
	String groupid = request.getParameter("groupid");
	String curriculumid = request.getParameter("curriculumid");
	String ohce = request.getParameter("ohce");
	String onec = request.getParameter("onec");
	String EngAppSend = request.getParameter("EngAppSend");
	String temp = null;
			
	if(EngAppSend.equals("null")){
		temp = "null";
	}else{
		temp = "'" + request.getParameter("EngAppSend") + "'";
	}
	
		
	System.out.println("courseId :" + courseId);////////////////try////////////////
	System.out.println("courseNameTH :" + courseNameTH);////////////////try////////////////
	System.out.println("courseNameEN :" + courseNameEN);////////////////try////////////////	
	System.out.println("credit :" + credit);////////////////try////////////////
	System.out.println("lecture :" + lecture);////////////////try////////////////
	System.out.println("lab :" + lab);////////////////try////////////////
	System.out.println("selfLearn :" + selfLearn);////////////////try////////////////
	System.out.println("details :" + details);////////////////try////////////////
	
	System.out.println("groupid :" + groupid);////////////////try////////////////
	System.out.println("curriculumid :" + curriculumid);////////////////try////////////////
	System.out.println("ohce :" + ohce);////////////////try////////////////
	System.out.println("onec :" + onec);////////////////try////////////////
	System.out.println("EngAppSend :" + EngAppSend);////////////////try////////////////
	System.out.println("temp :" + temp);////////////////try////////////////
	
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps+ "&characterEncoding=tis620");
		
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	/*Find Course in DB*/
	List<Course> course = new ArrayList<Course>();
	
	try{
		ResultSet rs_cour = connect.createStatement().executeQuery("SELECT `course_id` ,`group_id`,`curriculum_id`"
				+ " FROM course  "
				+ " WHERE curriculum_id="+ curriculumid +" AND group_id="+ groupid );
		
		while(rs_cour.next()) {
			Course cour = new Course();
			
			cour.setCourseId(rs_cour.getString("course_id"));			
			course.add(cour);
			
		}
		
	}catch (SQLException e) {
		e.printStackTrace();
	}
	/////////////////////////////////////////////////////
	int checker = 0; //0 = not Duplicate, 1 = Duplicate
	for(Course cou : course ) {	
		System.out.println("Course DB:  "+cou.getCourseId());
		System.out.println("Course Input:  "+courseId);
		
		if(cou.getCourseId().equals(courseId)){
			System.out.println("Duplicate ID:  "+courseId);
			System.out.println("////////////////////////////////////////////////////");
			checker = 1;
		}
	}
	
	////////////////////////////////////////////////////////////////////////////////
	if(checker == 0){
	// insert data to database			
	String sql_course = "INSERT INTO  `course`(`course_id`, `group_id`, `curriculum_id`, `course_name_th`, `course_name_en`, `credit`, `lecture_hour`, `lab_hour`, `self_learning_hour`, `detail`, `ohec_approved`, `onec_approved`,`curriculum_EngApp`)"
						+ " VALUES ('"+ courseId +"', "+ groupid +", "+ curriculumid +",'"+ courseNameTH + "', '"+ courseNameEN +"', "+ credit +", "+ lecture +", "+ lab +", "+ selfLearn +", '"+ details +"', '"+ ohce +"',  "+ temp +")";
			
			
	System.out.println(sql_course);/////////////////////try///////////////////////////////


		try {		
				// insert data into course 
				connect.createStatement().executeUpdate("INSERT INTO  `course`(`course_id`, `group_id`, `curriculum_id`, `course_name_th`, `course_name_en`, `credit`, `lecture_hour`, `lab_hour`, `self_learning_hour`, `detail`, `ohec_approved`, `onec_approved`,`curriculum_EngApp`)"
						+ " VALUES ('"+ courseId +"', "+ groupid +", "+ curriculumid +",'"+ courseNameTH + "', '"+ courseNameEN +"', "+ credit +", "+ lecture +", "+ lab +", "+ selfLearn +", '"+ details +"', '"+ ohce +"', '"+ onec +"', "+ temp +")");
	
					
				/* Log file */
				String log_user = strUser+" add course";
				Log.writeUserFile(log_user);
				Log.writeUserFile(sql_course);
				
			out.print("Success");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}else{
		System.out.println("/////////////DUPLICATE FILE//////////////");
		out.print("Failed");
	}
	
	connect.close();

%>